package com.aigou.controller;

import com.aigou.exception.AigouException;
import com.aigou.pojo.Result;
import com.aigou.pojo.User;
import com.aigou.service.UserService;
import com.aigou.utils.ImageVerificationCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;

@RestController
public class RegisterController {

    @Autowired
    UserService userService;
    @Autowired
    HttpSession session;
    @Autowired
    HttpServletResponse response;

    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public Result regester(String code, User user) {

        // session判断
        Object sessionCode = session.getAttribute("code");
        if (sessionCode == null || code == null) {
            throw new AigouException("验证码错误");
        }
        if (!code.equalsIgnoreCase(sessionCode.toString())) {
            throw new AigouException("验证码错误");
        }

        Result result = new Result();
        userService.add(user);
        return result;
    }

    @RequestMapping(value = "/createCode", method = RequestMethod.GET)
    public void createCode() throws IOException {

        ImageVerificationCode verificationCode = new ImageVerificationCode();
        BufferedImage image = verificationCode.getImage();
        String code = verificationCode.getText();
        // session判断
        session.setAttribute("code", code);
        ImageVerificationCode.output(image, response.getOutputStream());
    }

}
